<!--
 * @Descripttion: 人员预警
 * @version:
 * @Author: wl
 * @Date: 2020-05-21 17:00:50
 * @LastEditors: wl
 * @LastEditTime: 2020-07-31 15:12:04
-->
<template>
  <div>
    <page :asideShow="asideShow">
      <div slot="toolbar">
        <el-form :inline="true" :model="filters" label-width="90px" label-position="right">
          <el-form-item label="选择小区:">
            <el-select
              v-model="filters.CID"
              filterable
              placeholder="请选择"
              @keydown.enter.native="refreshPageRequest(1)"
              @change="refreshPageRequest(1)"
              clearable
            >
              <el-option
                v-for="item in villageList"
                :key="item.CID"
                :label="item.name"
                :value="item.CID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="预警类型：">
            <el-cascader
              :options="persign"
              @change="changeCascader"
              :props="{
                multiple: true,
                value: 'DID',
                label: 'name',
                children: 'dictionaries',
                checkStrictly: false,
                emitPath: true,
              }"
              collapse-tags
              :show-all-levels="false"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="预警事件">
            <el-select
              v-model="filters.warningEvent"
              filterable
              placeholder="请选择"
              @keydown.enter.native="refreshPageRequest(1)"
              @change="refreshPageRequest(1)"
              clearable
            >
              <el-option
                v-for="item in warnlist"
                :key="item.DID"
                :label="item.name"
                :value="item.DID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="姓名：">
            <el-input
              class="normal"
              placeholder="请输入名字"
              clearable
              v-model="filters.name"
              @keydown.enter.native="refreshPageRequest(1)"
            ></el-input>
          </el-form-item>
          <el-form-item label="设备名称">
            <el-select
              v-model="filters.equipment"
              filterable
              placeholder="请选择设备名称"
              @keydown.enter.native="refreshPageRequest(1)"
              @change="refreshPageRequest(1)"
              clearable
            >
              <el-option
                v-for="item in sblist"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态：">
            <el-select
              v-model="filters.status"
              filterable
              @change="refreshPageRequest(1)"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in statuss"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="起始时间：">
            <el-date-picker
              class="normal"
              v-model="filters.startTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间：">
            <el-date-picker
              class="normal"
              v-model="filters.endTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <div slot="btnSearch">
        <el-button type="primary" @click="refreshPageRequest(1)">查询</el-button>
      </div>
      <div slot="content">
        <el-table
          :header-cell-style="{ background: '#e7eaf0', color: '#606266' }"
          v-loading="loading"
          element-loading-text="加载中..."
          :data="blackList"
          style="width: 100%; margin-bottom: 20px"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection"></el-table-column>
          <el-table-column prop="pic" label="人像" width="100" align="center">
            <template slot-scope="scope">
              <img
                :src="
                  scope.row.person ? getItemPhoto(scope.row.person.photo) : ''
                "
                alt
                v-image-preview
                style="width: 50px; height: 50px"
              />
            </template>
          </el-table-column>
          <el-table-column prop="names" label="姓名" align="center">
            <template slot-scope="scope">
              <span>
                {{
                  scope.row.person.name
                }}
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="card" label="身份证号" align="center">
            <template slot-scope="scope">
              <span v-if="photoCheck == scope.row.photoCheck">
                {{
                  scope.row.person.idCard
                }}
              </span>
              <span v-else>{{ getItemIDCard(scope.row.person.idCard) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CID" label="所在小区" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="!villageList.length">-</span>
              <span v-else>
                {{
                  scope.row.CID ? (villageList.find((item) => {
                    return item.CID === scope.row.CID
                  }).name || scope.row.CID) : "-"
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="count" label="人员预警类型" align="center" width="150">
            <template slot-scope="scope">
              <span>
                {{
                  scope.row.warningType ? warnSign(scope.row.warningType) : "-"
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="count" label="预警事件" align="center" width="150">
            <template slot-scope="scope">
              <span>
                {{
                  scope.row.warningEvent ? warnEvent(scope.row.warningEvent) : "-"
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="deviceName"
            v-if="filters.warningEvent !== '4d9e2092-e5c5-4622-b6df-af87a23e7505'"
            label="设备名称"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span>{{ scope.row.device ? scope.row.device.Name : "-" }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="filters.warningEvent == '4d9e2092-e5c5-4622-b6df-af87a23e7505'"
            prop="insert_time"
            label="最后一次通行时间"
            align="center"
            width="180"
          >
            <template slot-scope="scope">
              <span>
                {{
                  scope.row.latelyTime && scope.row.latelyTime > 0
                    ? getItemUpdata(scope.row.latelyTime)
                    : "-"
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="filters.warningEvent == '4d9e2092-e5c5-4622-b6df-af87a23e7505'"
            prop="direction"
            label="最后一次通行方向"
            align="center"
            width="120"
          >
            <template slot-scope="scope">
              <span>
                {{
                  scope.row.direction
                    ? (scope.row.direction === 1 ? '进' : '出')
                    : "-"
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="insert_time" label="预警时间" align="center" width="250">
            <template slot-scope="scope">
              <span>
                {{
                  getItemUpdata(scope.row.insert_time)
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column align="center" width="150" label="操作" fixed="right">
            <template slot-scope="scope">
              <el-button v-if="scope.row.status == 2" size="mini" type="primary">已读</el-button>
              <!-- @click="xiangqing(scope.$index, scope.row)"详情 -->
              <el-button
                v-else
                size="mini"
                type="warning"
                v-show="hasPerm('news:blacklist:unread')"
                @click="Reading([scope.row._id])"
              >未读</el-button>
              <el-button
                v-show="hasPerm('news:blacklist:show')"
                size="mini"
                type="warning"
                @click="checkPhoto(scope.row)"
              >查看</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer">
        <!-- 批量删除 -->
        <el-button
          :disabled="selections.length === 0"
          type="danger"
          style="float: left"
          @click="Reading(selections)"
        >批量操作</el-button>
        <el-pagination
          layout="total, prev, pager, next, jumper"
          @current-change="refreshPageRequest"
          :current-page="pageRequest.page"
          :page-size="pageRequest.pageSize"
          :total="totalSize"
          style="float: right"
        ></el-pagination>
      </div>
    </page>

    <!-- 详情 -->
    <el-dialog title="人员详情" :visible.sync="addDialogVisible" width="35%">
      <el-form ref="form" :model="form" class="addform" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <span>{{ form.name }}</span>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <span>{{ form.phone ? getItemPhone(form.phone) : "/" }}</span>
        </el-form-item>
        <el-form-item label="证件号" prop="idCard">
          <span>{{ form.idCard ? getItemIDCard(form.idCard) : "/" }}</span>
        </el-form-item>
        <el-form-item label="人员类型" prop="type">
          <span>{{ form.type ? typeToName(form.type) : "/" }}</span>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <span>{{ form.birthday }}</span>
        </el-form-item>
        <el-form-item label="录入时间" prop="insertTime">
          <span>{{ getItemUpdata(form.insertTime) }}</span>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <span>{{ form.address ? form.address : "/" }}</span>
        </el-form-item>
        <el-form-item label="头像" prop="photo">
          <img
            style="width: 120px; height: 120px"
            v-if="this.form.photo"
            :src="getItemPhoto(this.form.photo)"
            class="avatar"
          />
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { format } from "@/utils/datetime";
import { Row } from "element-ui";
export default {
  data() {
    return {
      warnlist: [],
      persign: [],
      asideShow: false,
      unitShow: false,
      pageResult: [],
      filters: {
        CID: "",
        // corpName: "",
        name: "",
        startTime: "",
        endTime: "",
        warningType: [],
        warningEvent: "",
        equipment: ""
      },
      pageRequest: {
        page: 1,
        pageSize: 10,
      },
      sblist: [
        { label: "大门出", value: "1" },
        { label: "大门入", value: "2" },
      ],
      columns: [],
      loading: false,
      totalSize: 0,
      exportUrl: this.global.baseUrl + "/self_test_stat/export",
      exportLoading: false,
      // 小区列表
      villageList: [],
      // 列表
      blackList: [],
      // 弹框
      addDialogVisible: false,
      // 详情
      form: {},
      // 人员类型
      personList: [],
      photoCheck: 0,
      // 批量删除
      selections: [],
      statuss: [
        { label: "未读", value: "1" },
        { label: "已读", value: "2" },
      ],
    };
  },
  methods: {
    //查看
    checkPhoto(row) {
      if (row.photoCheck == this.photoCheck) {
        this.photoCheck = 0;
      } else {
        this.photoCheck = row.photoCheck;
      }
    },
    //名字脱敏
    formatName(name) {
      var newStr;
      if (name.length === 2) {
        newStr = name.substr(0, 1) + '*';
      } else if (name.length > 2) {
        var char = '';
        for (var i = 0, len = name.length - 2; i < len; i++) {
          char += '*';
        }
        newStr = name.substr(0, 1) + char + name.substr(-1, 1);
      } else {
        newStr = name;
      }
      return newStr;
    },
    // 头像处理
    getItemPhoto(id) {
      var url = this.global.baseUrlImage + "avatar/" + id;
      return url;
    },
    // 多选框
    handleSelectionChange(val) {
      this.selections = val.map(item => {
        return item._id
      });
    },
    // 时间处理
    getItemUpdata(id) {
      var updata = this.$format(id);
      return updata;
    },
    // 身份证处理
    getItemIDCard(id) {
      var idcard = id.replace(/(\d{4})\d*([0-9a-zA-Z]{4})/, "$1******$2");
      return idcard;
    },
    // 手机号处理
    getItemPhone(id) {
      var phone = id.slice(0, 4) + "****" + id.slice(7, 11) || "";
      return phone;
    },
    getdict() {
      this.warnlist = JSON.parse(
        sessionStorage.getItem("dictData")
      ).sys_early_warning;
      //
      this.persign = JSON.parse(
        sessionStorage.getItem("dictData")
      ).sys_person_sign;
    },
    // 预警事件
    warnEvent(row) {
      // this.warnlist.find((item) => {
      //   return item.DID == row
      // });

      for (let i = 0; i < this.warnlist.length; i++) {
        if (this.warnlist[i].DID == row) {
          return this.warnlist[i].name;
        }
      }
    },
    //预警类型
    warnSign(row) {
      for (let i = 0; i < this.persign.length; i++) {
        for (
          let index = 0;
          index < this.persign[i].dictionaries.length;
          index++
        ) {
          if (this.persign[i].dictionaries[index].DID == row) {
            return this.persign[i].dictionaries[index].name;
          }
        }
      }
    },
    //级联选择
    changeCascader(e) {
      let arr = [];
      arr = e.map(item => {
        return item[1]
      })
      this.filters.warningType = arr;

    },
    //已读操作
    Reading(e) {
      let that = this;
      this.$confirm("是否标记为已读？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$api.warn.sys_strategy_read({ arr: e }).then(
          res => {
            that.handleQuery();
          }
        )
      })
    },
    // 小区查询
    getCommunityList() {
      let params = {};
      params = {
        where: {
          CODES: [],
        },
      };
      let param = JSON.stringify(params);

      this.$api.three.communityList(params).then((res) => {
        if (res.code == 0) {

          this.villageList = res.data;

        } else {
          this.$message({ message: "操作失败, " + res.msg, type: "error" });
        }
      });
    },
    // 查询
    handleQuery(val) {
      this.loading = true;
      var params = Object.assign(this.filters, {
        page: val ? "" : this.pageRequest.page,
        limit: val ? "" : this.pageRequest.limit,
      });
      // params.strategy_type = =;
      params.isNotify = 1;
      let paramJson = JSON.stringify(params);
      this.$api.warn
        .strategy_log_list(paramJson)
        .then((res) => {
          if (res.code == 0) {
            this.blackList = res.data;
            this.blackList.map((item, index) => {
              item.person.names = this.formatName(item.person.name)
              item.photoCheck = index + 1
            })
            this.totalSize = res.count;
          }
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
          this.$message.error("网络超时");
        });
    },
    // 删除预警人员
    deletePer(index, row) {
      this.$confirm("确认删除选中记录吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        var params = {
          CID: row.person.CID,
          person_id: row.person.PID,
          strategy_type: 1,
        };
        let paramJson = JSON.stringify(params);
        this.$api.warn.deletewarn(paramJson).then((res) => {
          if (res.code == 0) {
            this.$message.warning("删除成功");
            this.handleQuery();
          } else {
            this.$message.info("删除失败");
          }
        });
      });
    },
    // 弹框
    xiangqing(index, row) {
      this.addDialogVisible = true;
      this.form = row.person;
    },
    // 匹配人员类型
    typeToName(type) {
      for (let index = 0; index < this.personList.length; index++) {
        var item = this.personList[index];
        if (type === item.DID) {
          return item.name;
        }
      }
      return "-";
    },

    // 批量删除
    batchDelete() {
      this.$confirm("确认删除选中用户吗？", "提示", "warning").then(() => {
        let selLength = this.selections.length;
        let totalLength = this.blackList.length;
        let isReduce = selLength == totalLength ? true : false;
        let params = this.selections
          .map((item) => {
            return item.PID;
          })
          .join(",");
        this.$api.personnel
          .batchDelete({
            IDS: params,
          })
          .then((res) => {
            if (res.code == 0) {
              this.$message.success("删除成功");
              if (isReduce) {
                this.pageRequest.page--;
              }
              this.handleQuery();
            } else {
              this.$message.error(res.msg);
            }
          });
      });
    },

    // 分页
    refreshPageRequest(page) {
      this.pageRequest.page = page;
      this.handleQuery();
    },
  },
  created() {
    this.filters.CID = localStorage.getItem("home_CID");
    this.getCommunityList();
    this.handleQuery();

    // 查询人员类型
    let diclist = JSON.parse(sessionStorage.getItem("dictData"));
    this.personList = diclist.sys_person_type;
    this.getdict();

    // console.log(this.personList, "人员的");
  },
  mounted() { },
};
</script>

<style>
</style>
